﻿using System;
using Coolite.Ext.Web;
using CooliteExamples.Code.DAL;
using CooliteExamples.Code.DTO;
using CooliteExamples.Core.Exceptions;
using CooliteExamples.Core.Extensions;
using CooliteExamples.Web.Code;

namespace CooliteExamples.Web.Pages.Control
{
		public partial class AuthorManage : PageBase
		{
				protected void Page_Load(object sender, EventArgs e)
				{
						if (!Ext.IsAjaxRequest && !IsPostBack)
						{
								LoadPage();
						}
				}

				private void LoadPage()
				{
						AuthorStore.Proxy.Add(new HttpProxy()
																																{
																																		DisableCaching = true,
																																		Json = true,
																																		Method = HttpMethod.GET,
																																		Url = Core.ProcessController.Handlers.Author.GetAuthorsHandlerUrl()
																																});
				}

				protected void btnSave_Click(object sender, AjaxEventArgs ev)
				{
						int authorId = hidAuthorId.Text.AsInt(0);
						string authorName = txtAuthorName.Text;

						AuthorDAL.SaveAuthor(new Author
																															{
																																	AuthorId = authorId,
																																	AuthorName = authorName
																															});
						ModifyAuthorWindow.Hide();
						AuthorStore.DataBind();
				}

				[AjaxMethod]
				public void DeleteAuthor(int authorId)
				{
						try
						{
								AuthorDAL.DeleteAuthor(new Author
																																			{
																																					AuthorId = authorId,
																																					AuthorName = string.Empty
																																			});
						}
						catch (BookManagerOperationException bex)
						{
								ScriptManager.AjaxSuccess = false;
								ScriptManager.AjaxErrorMessage = bex.Message;
						}
				}
		}
}
